package com.weijin.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weijin.pojo.MessageInfo;
import com.weijin.result.Result;
import com.weijin.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author WeiJin
 * @Version 1.0
 * @Date 2025/3/17 9:02
 */
@Configuration
@EnableWebSocket
@Slf4j
public class WebsocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(new SimpleChatHandler(), "/chat")
                .setAllowedOrigins("*");
    }

    public static class SimpleChatHandler extends TextWebSocketHandler {
        private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            String name = Objects.requireNonNull(session.getUri()).getQuery().split("=")[1];
            sessions.putIfAbsent(name, session);
            //建立连接获取在线用户
            Object[] objects = sessions.keySet().toArray();
            Result<Object> result = new Result<>();
            result.setCode(2000);
            result.setData(objects);

            //有新的连接广播所有人刷新用户列表
            for (WebSocketSession s : sessions.values()) {
                if (s.isOpen()) {
                    s.sendMessage(new TextMessage(objectMapper.writeValueAsString(result)));
                }
            }
            log.info("[websocket 消息] 有新的连接加入，连接总数：{}", sessions.size());
        }
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            log.info("[websocket 消息] 收到信息：{}", message.getPayload());
            //解析收到的信息
            MessageInfo sendMessageInfo = objectMapper.readValue(message.getPayload(), MessageInfo.class);
            //构建JSON聊天内容
            Result<Object> result = new Result<>();
            result.setCode(2001);
            sendMessageInfo.setSendTime(DateTimeUtil.datetimeToStr(LocalDateTime.now()));
            result.setData(sendMessageInfo);
            //单点信息
            WebSocketSession webSocketSession = sessions.get(sendMessageInfo.getReceiveUsername());
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(result)));
                log.info("[websocket 消息] 单点信息发送成功！");
            }
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            String key = sessions.entrySet().stream()
                    .filter(entry -> entry.getValue() == session)
                    .map(Map.Entry::getKey)
                    .findFirst()
                    .orElse(null);
            sessions.remove(key);
            log.info("[websocket 消息] 连接关闭，连接总数：{}", sessions.size());
        }
    }
}
